// This file is part of MinIO Console Server
// Copyright (c) 2019 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

import React, { useEffect, useState } from "react";
import { createStyles, Theme, withStyles } from "@material-ui/core/styles";
import clsx from "clsx";
import Grid from "@material-ui/core/Grid";
import Paper from "@material-ui/core/Paper";
import Typography from "@material-ui/core/Typography";
import FormControl from '@material-ui/core/FormControl';
import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import Select from '@material-ui/core/Select';
import InputBase from '@material-ui/core/InputBase';
import NetworkCheckIcon from "@material-ui/icons/NetworkCheck";
import PieChartIcon from "@material-ui/icons/PieChart";
import ViewHeadlineIcon from "@material-ui/icons/ViewHeadline";

import LocalDrinkIcon from "@material-ui/icons/LocalDrink";
import StorageIcon from "@material-ui/icons/Storage";
import TimelapseIcon from "@material-ui/icons/Timelapse";
import WidgetsIcon from "@material-ui/icons/Widgets";
import { Usage } from "./types";
import api from "../../../common/api";
import { niceBytes } from "../../../common/utils";
import { LinearProgress } from "@material-ui/core";
import { ChartUrl, beforeNowtimeByMinu } from "./types";
import ChartCPU from "./ChartCPU";
import ChartDisk from "./ChartDisk";
import ChartMem from "./ChartMem";
import ChartC from "./ChartC";
import ChartA from "./ChartA";
import Alerts from "./Alerts";
import D_NodeCPU from "./D_NodeCPU";
import D_NodeS3 from "./D_NodeS3";
import D_NodeNetTransRate from "./D_NodeNetTransRate";
import D_NodeReadWrite from "./D_NodeReadWrite";

const BootstrapInput = withStyles((theme: Theme) =>
  createStyles({
    root: {
      display: "flex",
      'label + &': {
        marginTop: 0,
        marginLeft: theme.spacing(4),
      },
    },
    input: {
      borderRadius: 4,
      position: 'relative',
      backgroundColor: theme.palette.background.paper,
      border: '1px solid #ced4da',
      fontSize: 14,
      padding: '1px 26px 1px 12px',
      transition: theme.transitions.create(['border-color', 'box-shadow']),
      '&:focus': {
        borderRadius: 4,
        borderColor: '#80bdff',
        boxShadow: '0 0 0 0.2rem rgba(0,123,255,.25)',
      },
    },
  }),
)(InputBase);
const styles = (theme: Theme) =>
  createStyles({
    toolbar: {
      paddingRight: 24, // keep right padding when drawer closed
    },
    toolbarIcon: {
      display: "flex",
      alignItems: "center",
      justifyContent: "flex-end",
      padding: "0 8px",
      ...theme.mixins.toolbar,
    },
    appBar: {
      zIndex: theme.zIndex.drawer + 1,
      transition: theme.transitions.create(["width", "margin"], {
        easing: theme.transitions.easing.sharp,
        duration: theme.transitions.duration.leavingScreen,
      }),
    },
    menuButton: {
      marginRight: 36,
    },
    menuButtonHidden: {
      display: "none",
    },
    title: {
      flexGrow: 1,
    },
    drawerPaperClose: {
      overflowX: "hidden",
      transition: theme.transitions.create("width", {
        easing: theme.transitions.easing.sharp,
        duration: theme.transitions.duration.leavingScreen,
      }),
      width: theme.spacing(7),
      [theme.breakpoints.up("sm")]: {
        width: theme.spacing(9),
      },
    },
    appBarSpacer: theme.mixins.toolbar,
    content: {
      flexGrow: 1,
      height: "100vh",
      overflow: "auto",
    },
    item: {
      "& h6": {
        fontSize: 18,
      },
    },
    container: {
      marginTop: theme.spacing(12),
      paddingBottom: theme.spacing(4),
      "& h6": {
        color: "#777777",
        fontSize: 14,
        fontWeight:"normal"
      },
      "& h4": {
        marginLeft:12
      },
      "& p": {
        "& span": {
          fontSize: 16,
        },
      },
    },
    paper: {
      padding: theme.spacing(1),
      display: "flex",
      overflow: "auto",
      flexDirection: "column",
    },
    dashtitle: {
      position: "absolute",
      top: "0",
      left: "0",
      width: "100%",
      height: "77px",
      lineHeight: "77px",
      justifyContent: "space-between",
      background: "#fff",
      borderBottom: "1px solid #e3e3e3"
    },
    dashh4: {
      marginLeft: "55px",
      lineHeight: "77px",
      color: "#000",
      fontSize: "18px",
      fontWeight: 700
    },
    serve: {
      width:"100%",
      padding: theme.spacing(1),
      paddingTop: theme.spacing(2),
      background: "#fff",
      borderRadius:"3px",
    },
    serveItem: {
      padding: theme.spacing(1),
      boxShadow: "none"
    },
    serveTitle: {
      marginLeft: theme.spacing(1),
      marginRight: theme.spacing(1),
      paddingLeft: theme.spacing(2),
      color: theme.palette.primary.main,
      fontSize: 14,
      borderLeft: "4px solid",
      borderColor: theme.palette.warning.main
    },
    over: {
      padding: theme.spacing(1),
    },
    overChart: {
      minHeight: 280,
      padding: 8,
      border: "1px solid #ddd",
      borderRadius: 5,
      background: "#efefef",
      overflow:"hidden"
    },
    consumptionValue: {
      // color: theme.palette.primary.main,
      fontSize: "18px",
      fontWeight: "bold",
      color: "#5793f3",
    },
    icon: {
      marginRight: 10,
      color: "#5793f3",
      borderRadius: "50%",
      background: "#efefef",
      width: "66px",
      height: "66px",
      lineHeight: "61px",
      textAlign: "center",
      border: "1px solid #ddd",
    },
    topIcon: {
      fontSize: "3rem",
      verticalAlign: "middle"
    },
    alerts: {
      position: 'absolute',
      margin: "60px 5%",
      width: "90%",
      minHeight: 500,
      padding: 0,
      backgroundColor: "#ffffff",
      borderRadius: "5px",
      boxShadow: "0px 5px 5px -3px rgba(0,0,0,0.2), 0px 8px 10px 1px rgba(0,0,0,0.14), 0px 3px 14px 2px rgba(0,0,0,0.12)",
      outline: "none"
    },
    alertsBtn: {
      marginRight: 12,
      border: "1px solid #002a37",
    },
    frame: {
      width: '100%',
      minHeight: 500,
      borderRadius: "5px",
      border: "none",
    },
    selItem: {
      marginRight: theme.spacing(1),
      flexDirection: "row",
      justifyContent: "flex-end"
    },
    selStep: {
      whiteSpace: "nowrap",
      lineHeight: "24px",
      fontSize: 14
    },
  })
interface IDashboardProps {
  classes: any;
}
export class Dashboard extends React.Component<IDashboardProps, any> {
  constructor(props:any){
    super(props);
    this.state = {
      loading: true,
      errinfo:"",
      step: "14",
      diskUsed:""
    };
  };
// const Dashboard = ({ classes }: IDashboardProps) => {
  // const fixedHeightPaper = clsx(classes.paper, classes.fixedHeight);
  // const [usage, setUsage] = useState<Usage | null>(null);
  // const [loading, setLoading] = useState<boolean>(true);
  // const [error, setError] = useState<string>("");

  // useEffect(() => {
  //   if (loading) {
  //     fetchUsage();
  //   }
  // }, [loading]);

  componentDidMount(): void {
    this.initialQuery()
    this.getDiskUsed()
  }
  initialQuery () {
    api
      .invoke("GET", `/api/v1/admin/info`)
      .then((res) => {
        this.setState({
          buckets: res.buckets.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","),
          objects: res.objects.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","),
          usage: niceBytes(res.usage),
          errinfo:"",
          loading:false
        })
      })
      .catch((err) => {
        this.setState({
          errinfo:err,
          loading:false
        })
      });
  };
  getDiskUsed() {
    let duration = 60;
    let step = this.state.step;
    if(step == '1'){
      duration = 15
    }else if(step == '7'){
      duration = 30
    }else if(step == '14'){
      duration = 60
    }else if(step == '28'){
      duration = 120
    }else if(step == '86'){
      duration = 360
    }else if(step == '172'){
      duration = 720
    }else if(step == '345'){
      duration = 1440
    }
    let url = ChartUrl+"disk_storage_used/(1024*1024*1024)&start="+Date.parse(beforeNowtimeByMinu(duration)).toString().substring(0,10)+"&end="+Date.parse(beforeNowtimeByMinu(0)).toString().substring(0,10)+"&step="+step;
    api
      .invoke("GET", url)
      .then((res) => {
        var rootData = res.data.result;
        if(rootData != []){
          for(var i=0;i<rootData.length;i++){
            for(var a=0;a<rootData[i].values.length;a++){
              rootData[i].values[a][1] = parseFloat(rootData[i].values[a][1]);
              rootData[0].values[a][1] += rootData[i].values[a][1]
            }
          }
          var x = rootData[0].values.length-1
          this.setState({
            diskUsed: parseFloat(rootData[0].values[x][1].toFixed(2)),
          });
        }else{
        }
      })
      .catch(err => {
      });
  }
  // const prettyUsage = (usage: string | undefined) => {
  //   if (usage === undefined) {
  //     return "0";
  //   }
  //   return niceBytes(usage);
  // };

  // const prettyNumber = (usage: number | undefined) => {
  //   if (usage === undefined) {
  //     return 0;
  //   }

  //   return usage.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  // };
  
render() {
  const { classes } = this.props;
  var handleChangeQueryUrl = (event: React.ChangeEvent<{ value: unknown }>) => {
    this.setState({ 
      step: event.target.value
    });

  };
  return (
    <React.Fragment>
      <Grid container className={classes.dashtitle}>
        <Typography variant="h4" className={classes.dashh4}>Dashboard</Typography>
        {/* <Button type="button" color="primary" onClick={handleOpen} className={classes.alertsBtn}>
          告警
        </Button> */}
        <Alerts/>
      </Grid>
      <Grid container>
        <Grid container spacing={3} className={classes.container}>
          {this.state.error !== "" && <Grid container>{this.state.errorinfo}</Grid>}
          {this.state.loading ? (
            <Grid item xs={12} md={12} lg={12}>
              <LinearProgress />
            </Grid>
          ) : (
            <React.Fragment>
              <Grid container style={{padding: 12}}>
                <Paper className={classes.serve}>

                  <Grid container direction="row" alignItems="center">
                    <Typography variant="subtitle1" className={classes.serveTitle}>服务概况</Typography>
                  </Grid>

                  <Grid container>
                    <Grid item style={{width:"25%"}}>
                      <Paper className={classes.serveItem}>
                        <Grid container direction="row" alignItems="center">
                          <Grid item className={classes.icon}>
                            <LocalDrinkIcon className={classes.topIcon}/>
                            {/* <ViewHeadlineIcon className={classes.topIcon}/> */}
                          </Grid>
                          <Grid item>
                            <Typography variant="h6">桶总数</Typography>
                            <Typography className={classes.consumptionValue}>
                              {this.state.buckets ? this.state.buckets : 0}
                            </Typography>
                          </Grid>
                        </Grid>
                      </Paper>
                    </Grid>
                    <Grid item style={{width:"25%"}}>
                      <Paper className={classes.serveItem}>
                        <Grid container direction="row" alignItems="center">
                          <Grid item className={classes.icon}>
                            <WidgetsIcon  className={classes.topIcon}/>
                            {/* <NetworkCheckIcon  className={classes.topIcon}/> */}
                            {/* VerticalSplit LocalDrink*/}
                          </Grid>
                          <Grid item>
                            <Typography variant="h6"> 总对象</Typography>
                            <Typography className={classes.consumptionValue}>
                              {this.state.objects ? this.state.objects : 0}
                            </Typography>
                          </Grid>
                        </Grid>
                      </Paper>
                    </Grid>
                    <Grid item style={{width:"25%"}}>
                      <Paper className={classes.serveItem}>
                        <Grid container direction="row" alignItems="center">
                          <Grid item className={classes.icon}>
                            <TimelapseIcon  className={classes.topIcon}/>
                            {/* <PieChartIcon  className={classes.topIcon}/> */}
                          </Grid>
                          <Grid item>
                            <Typography variant="h6">已用</Typography>
                            <Typography className={classes.consumptionValue}>
                              {this.state.usage ? this.state.usage + "" : 0}
                            </Typography>
                          </Grid>
                        </Grid>
                      </Paper>
                    </Grid>
                    <Grid item style={{width:"25%"}}>
                      <Paper className={classes.serveItem}>
                        <Grid container direction="row" alignItems="center">
                          <Grid item className={classes.icon}>
                            <StorageIcon  className={classes.topIcon}/>
                          </Grid>
                          <Grid item>
                            <Typography variant="h6">硬盘已存储</Typography>
                            <Typography className={classes.consumptionValue}>
                              {this.state.diskUsed ? this.state.diskUsed + "GB" : 0}
                            </Typography>
                          </Grid>
                        </Grid>
                      </Paper>
                    </Grid>
                  </Grid>
                </Paper>
              </Grid>
              {/* 容量概况 - start */}
              <Grid container style={{padding: 12}}>
                <Paper className={classes.serve}>
                  <Grid container style={{justifyContent: "space-between"}}>
                    <Typography variant="subtitle1" className={classes.serveTitle}>容量概况</Typography>

                    <FormControl className={classes.selItem}>
                      <Typography className={classes.selStep}>选择时长：</Typography>
                      <Select
                        labelId="time"
                        id="timeinstanceSel"
                        value={this.state.step}
                        onChange={handleChangeQueryUrl}
                        input={<BootstrapInput />}
                        style={{width: "80px"}}
                      >
                        <MenuItem value="14">
                          <em>1h</em>
                        </MenuItem>
                        <MenuItem value={"1"}>15min</MenuItem>
                        <MenuItem value={"7"}>30min</MenuItem>
                        <MenuItem value={"14"}>1h</MenuItem>
                        <MenuItem value={"28"}>2h</MenuItem>
                        <MenuItem value={"86"}>6h</MenuItem>
                        <MenuItem value={"172"}>12h</MenuItem>
                        <MenuItem value={"345"}>1d</MenuItem>
                      </Select>
                    </FormControl>
                  </Grid>
                  <Grid container>
                    
                    {/* <Grid item xs={12} md={6} lg={4} className={classes.over}>
                      <div className={classes.overChart}>
                        <Grid container direction="row" alignItems="center" justify="center">
                          <Typography variant="h6">接收的s3字节总数</Typography>
                        </Grid>
                        <ChartC inputStep={this.state.step}/>
                      </div>
                    </Grid> */}
                    <Grid item style={{width:"33.3%"}} className={classes.over}>
                      <div className={classes.overChart}>
                        <Grid container direction="row" alignItems="center" justify="center">
                          <Typography variant="h6">硬盘总存储</Typography>
                        </Grid>
                        <ChartDisk inputStep={this.state.step}/>
                      </div>
                    </Grid>
                    <Grid item style={{width:"33.3%"}} className={classes.over}>
                      <div className={classes.overChart}>
                        <Grid container direction="row" alignItems="center" justify="center">
                          <Typography variant="h6">内存使用率</Typography>
                        </Grid>
                        <ChartMem inputStep={this.state.step}/>
                      </div>
                    </Grid>
                    <Grid item style={{width:"33.4%"}} className={classes.over}>
                      <div className={classes.overChart}>
                        <Grid container direction="row" alignItems="center" justify="center">
                          <Typography variant="h6">CPU平均使用率</Typography>
                        </Grid>
                        <ChartCPU inputStep={this.state.step}/>
                      </div>
                    </Grid>
                    {/* <Grid item xs={12} md={6} lg={4} className={classes.over}>
                      <div className={classes.overChart}>
                        <ChartA inputStep={this.state.step}/>
                      </div>
                    </Grid> */}
                  </Grid>
                </Paper>
              </Grid>
              {/* 容量概况 - end */}

              {/* 负载概况 - start */}
              <Grid container style={{padding: 12}}>
                <Paper className={classes.serve}>
                  <Grid container style={{justifyContent: "space-between"}}>
                    <Typography variant="subtitle1" className={classes.serveTitle}>负载概况</Typography>
                  </Grid>
                  <Grid container>
                    <Grid item  style={{width:"25%"}} className={classes.over}>
                      <div className={classes.overChart}>
                        <Grid container direction="row" alignItems="center" justify="center">
                          <Typography variant="h6">CPU使用率</Typography>
                        </Grid>
                        <D_NodeCPU/>
                      </div>
                    </Grid>
                    <Grid item  style={{width:"25%"}} className={classes.over}>
                      <div className={classes.overChart}>
                        <Grid container direction="row" alignItems="center" justify="center">
                          <Typography variant="h6">接发的s3字节总数</Typography>
                        </Grid>
                        <D_NodeS3/>
                      </div>
                    </Grid>
                    <Grid item  style={{width:"25%"}} className={classes.over}>
                      <div className={classes.overChart}>
                        <Grid container direction="row" alignItems="center" justify="center">
                          <Typography variant="h6">网络传输速率</Typography>
                        </Grid>
                        <D_NodeNetTransRate/>
                      </div>
                    </Grid>
                    <Grid item  style={{width:"25%"}} className={classes.over}>
                      <div className={classes.overChart}>
                        <Grid container direction="row" alignItems="center" justify="center">
                          <Typography variant="h6">磁盘读写I/O</Typography>
                        </Grid>
                        <D_NodeReadWrite/>
                      </div>
                    </Grid>
                  </Grid>
                </Paper>
              </Grid>
              {/* 负载概况 - end */}
            </React.Fragment>
          )}
        </Grid>
      </Grid>
    </React.Fragment>
  );
};
};

export default withStyles(styles)(Dashboard)